﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;
using ExtAspNet;
using System.Data;
using Newtonsoft.Json.Linq;
using AspNet = System.Web.UI.WebControls;


namespace TCMSystem.admin
{
    public partial class role_menu : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Module

        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.CoreRoleMenu;
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerEditWithButton(btnGroupUpdate);


            // 每页记录数
            Grid1.PageSize = TblMstConfigHelper.PageSize;
            BindGrid();
            // 默认选中第一个角色
            Grid1.SelectedRowIndex = 0;

            // 每页记录数
            Grid2.PageSize = TblMstConfigHelper.PageSize;
            BindGrid2();
        }

        private void BindGrid()
        {
            SqlQuery q = new Select().From<TblMstRole>();
            q.Where("1").IsEqualTo("1");

            // 排列
            q.OrderBys.Add(GetSortExpression(Grid1, TblMstRole.Schema));

            TblMstRoleCollection items = q.ExecuteAsCollection<TblMstRoleCollection>();

            Grid1.DataSource = items;
            Grid1.DataBind();
        }

        private void BindGrid2()
        {
            List<CustomMenu> menus = new List<CustomMenu>();

            int roleId = GetSelectedRoleId();
            if (roleId > 0)
            {
                List<int> menuIds = RoleMenuHelper.GetRoleMenus(roleId);

                menus = CustomMenuHelper.GetCustomMenus();

                foreach (CustomMenu customMenu in menus)
                {
                    if (menuIds.Contains(customMenu.Id))
                    {
                        customMenu.IsShow = true;
                    }
                    else
                    {
                        customMenu.IsShow = false;
                    }
                }

            }
            else
            {
                Grid2.RecordCount = 0;
            }

            Grid2.DataSource = menus;
            Grid2.DataBind();
        }


        protected string GetModuleName(object moduleNameObj)
        {
            if (moduleNameObj == null) 
            {
                return String.Empty;
            }

            string moduleName = moduleNameObj.ToString();
            if (moduleName == "None")
            {
                return String.Empty;
            }
            return moduleName;
        }

        #endregion

        #region Private

        /// <summary>
        /// 获取选中的角色ID（没有则返回-1）
        /// </summary>
        /// <returns></returns>
        private int GetSelectedRoleId()
        {
            int roleId = -1;
            int rowIndex = Grid1.SelectedRowIndex;
            if (rowIndex >= 0)
            {
                roleId = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);
            }
            return roleId;
        }

        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortColumnIndex = e.ColumnIndex;
            BindGrid();

            // 默认选中第一个角色
            Grid1.SelectedRowIndexArray = new int[] { 0 };

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, ExtAspNet.GridRowClickEventArgs e)
        {
            BindGrid2();
        }

        #endregion

        #region Grid2 Events


        protected void btnGroupUpdate_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPowerEdit())
            {
                CheckPowerFailWithAlert();
                return;
            }

            int roleId = GetSelectedRoleId();

            // 首先从TblMstRolemenu表中删除所有记录
            TblMstRolemenu.Delete(TblMstRolemenu.RoleIdColumn.ColumnName, roleId);

            // 添加所有记录
            ExtAspNet.CheckBoxField showField = Grid2.FindColumn("showField") as ExtAspNet.CheckBoxField;

            TblMstRolemenuCollection roleMenus = new TblMstRolemenuCollection();
            foreach (GridRow row in Grid2.Rows)
            {
                int rowIndex = row.RowIndex;

                object[] dataKeys = Grid2.DataKeys[rowIndex];
                int menuId = Convert.ToInt32(dataKeys[0]);

                bool isShow = showField.GetCheckedState(rowIndex);

                if (isShow)
                {
                    TblMstRolemenu roleMenu = new TblMstRolemenu();
                    roleMenu.RoleId = roleId;
                    roleMenu.MenuId = menuId;

                    roleMenus.Add(roleMenu);
                }

            }
            roleMenus.BatchSave();

            // 更新缓存
            RoleMenuHelper.UpdateRoleMenus(roleId);


            Alert.ShowInTop("当前角色的显示菜单更新成功！");
        }



        protected void btnSelectCheckbox_Click(object sender, EventArgs e)
        {
            SelectAll(true);
        }


        protected void btnUnSelectCheckbox_Click(object sender, EventArgs e)
        {
            SelectAll(false);
        }


        private void SelectAll(bool selected)
        {
            ExtAspNet.CheckBoxField showField = Grid2.FindColumn("showField") as ExtAspNet.CheckBoxField;

            for (int i = 0; i < Grid2.Rows.Count; i++)
            {
                showField.SetCheckedState(i, selected);
            }

            Grid2.UpdateTemplateFields();
        }

        #endregion

    }
}
